#pragma once 

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include "Err.hpp"

static const int backlog = 32;

class Sock
{
public:
    // 1. 创建socket文件套接字对象
    static int Socket()
    {
        int sock = socket(AF_INET,SOCK_STREAM,0);
        if(sock < 0)
        {
            logMessage(FATAL,"socket create error");
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL,"socket create success: %d",sock);

        int opt = 1;
        setsockopt(sock,SOL_SOCKET,SO_REUSEADDR | SO_REUSEPORT,&opt,sizeof opt);

        return sock;    
    }

    // 2.bind自己的网络信息
    static void Bind(int sock,const uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local,0,sizeof local);

        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(port);

        int n = bind(sock,(struct sockaddr*)&local,sizeof local);
        if(n < 0)
        {
            logMessage(FATAL,"socket bind error");
            exit(BIND_ERR);
        }
        logMessage(NORMAL,"socket bind success");
    }

    // 3. 设置socket 为监听状态
    static void Listen(int sock)
    {
        int n = listen(sock,backlog);
        if(n < 0)
        {
            logMessage(FATAL,"socket listen error");
            exit(LISTEN_ERR);
        }
        logMessage(NORMAL,"socket listen success");
    }

    static int Accept(int listensock,std::string* clientip,uint16_t* clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sock = accept(listensock,(struct sockaddr*)&peer,&len);
        if(sock < 0)
        {
            logMessage(ERROR,"socket accept error,next");
        }
        else
        {
            logMessage(NORMAL,"accept a new link success, get a new sock: %d",sock);
            *clientip = inet_ntoa(peer.sin_addr);
            *clientport = ntohs(peer.sin_port);
        }

        return sock;
    }
};